/**
 * Created by Heiliuer on 2019/4/7 0007.
 */
import React from 'react'
import './index.css'

class LineChart extends React.Component {

    constructor(...args) {
        super(...args)
        this.state = {
            key: String(Math.random()).split('.')[1] + Date.now()
        }
    }

    /**
     * @param xData x轴数据
     * @param yData y轴数据
     */
    initChart(props = this.props) {
        const {
            title = {},
            legend = {
                data: []
            },
            xAxis = {
                data: []
            },
            series = []
        } = props
        // 数据为空，则不初始化图表
        if (!series || !series.length) {
            return
        }

        const option = {
            title: {
                ...title
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                ...legend
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    // 显示保存图表为图片按钮
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisLabel: {formatter: '{value} 分钟'},
                ...xAxis
            },
            yAxis: {
                type: 'value'
            },
            series
        }
        const init = () => {
            this.chart = window.echarts.init(this.chartDom)
            this.chart.setOption(option)
        }
        // 图表实例未初始化，则初始化
        if (!this.chart) {
            init()
        } else {
            this.setState({
                key: String(Math.random()).split('.')[1] + Date.now()
            }, init)
        }
    }

    componentDidMount() {
        // 初始化图表
        this.initChart()
        window.addEventListener('resize', () => {
            if (this.chart) {
                this.chart.resize()
            }
        })
    }

    componentWillReceiveProps(nextProps, nextContext) {
        this.initChart(nextProps)
    }

    render() {
        const {className} = this.props
        return <div className="line-chart-wrapper">
            <div key={this.state.key} className={'line-chart ' + (className || '')}
                 ref={/*通过ref获取到组件的dom*/dom => this.chartDom = dom}></div>
        </div>
    }
}

export default LineChart